package pc

import (
	"chess_platform/controllers"
	"chess_platform/internal/alisdk"
	. "chess_platform/internal/common"
	"chess_platform/internal/token"
	"chess_platform/models/client"
	"chess_platform/models/h5"
	"chess_platform/models/partner"
	"chess_platform/models/pc"
	"fmt"
	"strconv"
	"time"
)

//需要token,但不需要过权限模块
type PublicController struct {
	GrantController
}

func (b *PublicController) URLMapping() {
	b.Mapping("ListGroup", b.ListGroup)
	b.Mapping("RefreshToken", b.RefreshToken)
	b.Mapping("ServerConf", b.ServerConf)
	b.Mapping("UserInfo", b.UserInfo)
	b.Mapping("UpdateUser", b.UpdateUser)
	b.Mapping("ListMenu", b.ListMenu)
	b.Mapping("UploadFileToOSS", b.UploadFileToOSS)

	//------------------------------以下是玩家方面的公共权限-----------------------
	//player:玩家
	b.Mapping("Info", b.Info)
	b.Mapping("ListDayTransDetail", b.ListDayTransDetail)
	b.Mapping("ListGame", b.ListGame)
	b.Mapping("ListPlayerLoginLog", b.ListPlayerLoginLog)
	b.Mapping("ListPlayerOrder", b.ListPlayerOrder)
	b.Mapping("ListPlayerRecord", b.ListPlayerRecord)
	b.Mapping("RecordDetail", b.RecordDetail)
	b.Mapping("UpdatePlayerUser", b.UpdatePlayerUser)
	b.Mapping("ListDiamondDetail", b.ListPlayerDiamondDetail)
	b.Mapping("ListPlayerPlayer", b.ListPlayerPlayer)

	//------------------------------以下是代理方面的公共权限-----------------------
	//formal:正式代理
	b.Mapping("ListChildAgent", b.ListChildAgent)
	b.Mapping("AgentDetail", b.AgentDetail)
	b.Mapping("ListWithdraw", b.ListWithdraw)
	b.Mapping("ListAgentDiamondDetail", b.ListAgentDiamondDetail)
	b.Mapping("ListChildCash", b.ListChildCash)
	b.Mapping("ListAgentShopOrder", b.ListAgentShopOrder)

	b.Mapping("ListCashMonth", b.ListCashMonth)
	b.Mapping("ListCashDetail", b.ListCashDetail)
	b.Mapping("ListAgentLoginLog", b.ListAgentLoginLog)
	b.Mapping("ListOfficialH5User", b.ListOfficialH5User)
	b.Mapping("ListSingleAgentOrder", b.ListSingleAgentOrder)
	b.Mapping("ListAgentPlayer", b.ListAgentPlayer)
}

func (b *PublicController) Prepare() {
	LogPc.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogPc.Debug("用户访问url:" + b.Ctx.Input.URL())
	b.Res = new(controllers.Response)
	var (
		t        controllers.Token
		tokenStr string
		ex       *token.Export
	)

	err := b.Unmarshal(&t)
	if err != nil || t.Token == "" {
		tokenStr = b.Ctx.Input.Header("token")
		if tokenStr == "" {
			tokenStr = b.Ctx.Request.PostFormValue("token")
		}
	}
	if tokenStr != "" {
		ex, err = token.Parse(tokenStr)
	} else {
		tokenStr = t.Token
		ex, err = token.Parse(t.Token)
	}

	if err != nil || ex.GetTokenType() != TokenPc {
		LogPc.Error(fmt.Sprintf("token解析错误:%v,或不是此Pc类型的token", err))
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}

	b.Uid = ex.GetId()
	b.Level = ex.GetLevel()

	//cache里不存在说明token已经过期了
	key := fmt.Sprintf("%v%v", KeyPcTokenCache, b.Uid)
	if ex.IsExpire() || !RedisCache.IsExist(key) {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserExpire
		b.Response()
		return
	}

	//cache里的token与传进来的不一样的话表示此帐号在其它地方登录了
	tokenCache := RedisCache.GetString(key)
	if tokenCache != "" { // token存在缓存里
		if string(tokenCache) != tokenStr {
			b.Res.Code = ErrAlreadyLogin
			b.Res.Msg = MsgErrAlreadyLogin
			b.Response()
			return
		}
	} else { //token不存在缓存里
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}

	keyAccessLimit := fmt.Sprintf("PcUserLimit-%v", b.Uid)
	if !AccessLimit(keyAccessLimit, Al.Frequency, Al.ExpireTime) {
		b.ResponseFail("操作过于频繁，请稍候再操作")
		return
	}

	v, ok := ex.GetInfo().(map[string]interface{})
	if ok {
		roleId := fmt.Sprintf("%v", v["role_id"])
		groupId := fmt.Sprintf("%v", v["group_id"])
		b.Ui.RoleId, _ = strconv.ParseInt(roleId, 10, 64)
		b.Ui.GroupId, _ = strconv.ParseInt(groupId, 10, 64)
	} else {
		b.ResponseFail("系统异常")

		return
	}
	LogPc.Debug(fmt.Sprintf("用户Uid:%d", b.Uid))
	LogPc.Debug(fmt.Sprintf("用户访问roleId:%d", b.Ui.RoleId))
	LogPc.Debug(fmt.Sprintf("用户访问groupId:%d", b.Ui.GroupId))

}

// @Title 获取大区列表
// @Description 获取大区列表
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Success 0 {object} []common.Group 代理用户列表
// @router /list-group [post]
func (b *PublicController) ListGroup() {
	var p ListParams
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	data, count, err := pc.ListGroup(p)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = data
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 刷新token(定时刷新,每隔30分钟)
// @Description 刷新token(定时刷新,每隔30分钟)
// @Success 0 {string} 状态
// @router /refresh-token [post]
func (b *PublicController) RefreshToken() {
	tokenStr := token.Create(b.Uid, b.Level, TokenPc, b.Ui)
	key := fmt.Sprintf("%v%v", KeyPcTokenCache, b.Uid)
	RedisCache.Put(key, tokenStr, time.Duration(Secret.TokenExpire)*time.Second)
	b.Res.Token = tokenStr
	b.ResponseSuccess()
}

// @Title 服务器参数
// @Description 服务器参数
// @Success 0 {object} common.ServerConf 服务器参数
// @router /server-conf [post]
func (b *PublicController) ServerConf() {
	serverConf := ServerConf{
		Region:     alisdk.GetOssRegion(),
		Bucket:     alisdk.GetOssBucketName(),
		OssRootUrl: alisdk.GetOssPathUrl(OssDomain),
	}
	b.Res.Data = serverConf
	b.ResponseSuccess()
}

// @Title 用户详情
// @Description 用户详情
// @Success 0 {object} common.PcUser 用户信息
// @router /user-info [post]
func (b *PublicController) UserInfo() {
	user, err := pc.UserInfoById(b.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))

		return
	}
	b.Res.Data = map[string]interface{}{
		"email":     user.Email,
		"real_name": user.RealName,
		"name":      user.Name,
	}
	b.ResponseSuccess()
}

// @Title 更新用户(密码,邮箱)(pc端)
// @Description 更新用户(密码,邮箱)(pc端)
// @Param   email    	body    string  true      "邮件"
// @Param   password 	body    string  true      "密码"
// @Success 0 {string} 状态码
// @Failure 399
// @router /update-user [post]
func (b *PublicController) UpdateUser() {
	type Params struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}

	if p.Password != "" {
		b.Valid.MinSize(p.Password, 6, "password").Message("密码长度为6-15个字符")
		b.Valid.MaxSize(p.Password, 15, "password").Message("密码长度为6-15个字符")
	}
	if p.Email != "" {
		b.Valid.Email(p.Email, "email").Message("请输入正确的邮箱")
	}
	if !b.VerifyParamsError() {
		return
	}
	user := map[string]interface{}{
		"email": p.Email,
	}
	if p.Password != "" {
		user["password"] = Md5sum(p.Password)
	}
	_, err := pc.UpdateUser(user, b.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.ResponseSuccess()
	msg := fmt.Sprintf("用户更新自己的个人信息")
	b.NewLog(LogPcUser, OpUpdate, msg, map[string]interface{}{})
}

// @Title 角色菜单
// @Description 角色菜单
// @Success 0 {string} 状态码
// @Failure 399
// @router /list-menu [post]
func (b *PublicController) ListMenu() {
	role, err := pc.RoleAuthorizedInfo(b.Uid, b.IsSystemAdmin())
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = pc.SimplifyPermission(role)
	b.ResponseSuccess()
}

// @Title 上传文件图片
// @Description 上传文件图片
// @Param   file        body   string     true       "上传的文件名字"
// @Param   module      body   string     true       "模块名,公告:Notice,游戏配置:Game,客服:CustomerService"
// @Success 0 {string} 状态码
// @router /upload [post]
func (b *PublicController) UploadFileToOSS() {
	f, h, err := b.GetFile("file")
	if err != nil {
		b.ResponseFail(err.Error())
		return
	}
	module := b.Ctx.Request.PostFormValue("module")
	savePath := GetPathByModule(module)
	if savePath == "" {
		b.ResponseFail("模块名输入有误")
		return
	}
	defer f.Close()
	ossPath, err := alisdk.UploadFileToOss(f, h.Filename, PlatformRunMode+savePath, b.Uid)
	if err != nil {
		b.ResponseFail(err.Error())
		return
	}
	b.Res.Data = ossPath
	b.ResponseSuccess("上传成功")
}

func GetPathByModule(moduleName string) string {
	switch moduleName {
	case "Notice":
		return "/notice"
	case "Game":
		return "/game"
	case "CustomerService":
		return "/customer_service"
	}
	return ""
}

//------------------------------以下是玩家方面的公共权限-----------------------
// @Title 获取玩家信息
// @Description 获取玩家信息
// @Param   uid  body    int     true      "用户uid"
// @Success 0 {object} client.User
// @router /player/info [post]
func (b *PublicController) Info() {
	type Params struct {
		Uid int64 `json:"uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	dbUser, err := client.UserInfoById(p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = dbUser
	b.ResponseSuccess()

}

// @Title 获取每日金流列表(某个用户的金流详细信息)
// @Description  获取每日金流列表((某个用户的金流详细信息))
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   day    		 body   int     true       "哪一天的时间戳"
// @Param   uid    		 body   int     true       "玩家id"
// @Success 0 {object} [] 每日金流(详细)
// @router /player/list-day-trans-detail [post]
func (b *PublicController) ListDayTransDetail() {
	type Params struct {
		ListParams
		Day int64 `json:"day"`
		Uid int64 `json:"uid"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	if p.Day == 0 {
		p.Day = time.Now().Unix()
	}
	data, count, err := pc.ListDayTransDetail(p.ListParams, p.Day, p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = data
	b.Res.Count = count
	b.ResponseSuccess()

}

// @Title 游戏列表(游戏发布)
// @Description 游戏列表(游戏发布)
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Success 0 {object} []common.GameList 游戏列表
// @router /player/list-game [post]
func (b *PublicController) ListGame() {
	var p ListParams
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	data, count, err := pc.ListGame(p, 0)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = data
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取玩家登录日志详细
// @Description 获取玩家登录日志详细
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   start_time   body   int     false      "开始时间"
// @Param   end_time     body   int     false      "结束时间"
// @Param   uid          body   int     true       "玩家id"
// @Success 0 {object} [] 登录日志
// @router /player/list-player-login-log [post]
func (b *PublicController) ListPlayerLoginLog() {
	type Params struct {
		ListParams
		ListDayParams
		Uid int64 `json:"uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	users, count, err := pc.PlayerLoginLog(p.ListParams, p.ListDayParams, p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = users
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 玩家的订单列表(H5店铺及商城里的支付记录)
// @Description 玩家的订单列表(H5店铺及商城里的支付记录)
// @Param   type               body   int     true       "0-店铺支付记录,1-商城支付记录"
// @Param   start_time         body   int     false      "下单开始时间"
// @Param   end_time           body   int     false      "下单结束时间"
// @Param   page_size          body   int     true       "每页显示数量"
// @Param   page_index         body   int     true       "第几页"
// @Param   uid          	   body   int     true       "用户id"
// @Param   transaction_id     body   string  false      "微信订单号"
// @Param   id                 body   int     false      "平台订单号"
// @Param   status             body   int     false      "订单状态,0-所有状态,1-未支付,2-已关闭,3-支付错误,4-支付成功,未发货,5-已发货'"
// @Success 0 {object} []common.Order 订单(支付)列表
// @router /player/list-player-order [post]
func (b *PublicController) ListPlayerOrder() {
	type Params struct {
		Type int64 `json:"type" valid:"Range(0,1)"`
		ListParams
		ListDayParams
		AllOrderParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	if p.Type == 0 {
		cr, count, err := pc.ListPlayerH5Order(p.ListParams, p.ListDayParams, p.AllOrderParams)
		if err != nil {
			LogPc.Error(b.DatabaseError(err.Error()))
			return
		}
		b.Res.Data = cr
		b.Res.Count = count
	} else {
		cr, _, count, err := pc.ListAppOrder(p.ListParams, p.ListDayParams, p.AllOrderParams)
		if err != nil {
			LogPc.Error(b.DatabaseError(err.Error()))
			return
		}
		b.Res.Data = cr
		b.Res.Count = count
	}
	b.ResponseSuccess()
}

// @Title 获取玩家战绩列表
// @Description 获取玩家战绩列表
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   start_time   body   int     true       "开始时间"
// @Param   end_time     body   int     true       "结束时间"
// @Param   uid          body   int     true       "搜索玩家id"
// @Param   game_id      body   string  false      "搜索游戏"
// @Success 0 {object} [] 战绩列表
// @router /player/list-player-record [post]
func (b *PublicController) ListPlayerRecord() {
	type Params struct {
		ListParams
		ListDayParams
		Uid    int64 `json:"uid" valid:"Required"`
		GameId int64 `json:"game_id"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	var gameType, playType int
	if p.GameId != 0 {
		gameType, playType = AnalysisGameId(p.GameId)
	}
	data, count, err := pc.PlayerRecord(p.ListParams, p.ListDayParams, p.Uid, gameType, playType)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = data
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取战绩详情
// @Description 获取战绩详情
// @Param   table_id  	   body    int  true      "桌子ID"
// @Success 0
// @Failure 400
// @Failure 404
// @router /player/record-detail [post]
func (b *PublicController) RecordDetail() {
	type Params struct {
		TableId int64 `json:"table_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	detail, err := pc.RecordDetail(p.TableId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = detail
	b.ResponseSuccess()
}

// @Title 更新玩家数据
// @Description 更新玩家数据
// @Param   uid            body    int     true      "玩家uid"
// @Param   vip            body    string  true      "玩家等级,0-普通,1-vip"
// @Param   phone          body    string  true      "手机号"
// @Param   password       body    string  true      "密码,传空表示不修改密码"
// @Success 0 {string} 状态码
// @router /player/update-user [post]
func (b *PublicController) UpdatePlayerUser() {
	type Params struct {
		Uid      int64  `json:"uid" valid:"Required"`
		Vip      int64  `json:"vip"`
		Phone    string `json:"phone"`
		Password string `json:"password"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	b.Valid.Min(p.Vip, 0, "vip").Message("vip等级最小值为0")
	if p.Phone != "" {
		b.Valid.Phone(p.Phone, "phone").Message("请输入正确的手机号")
	}
	if !b.VerifyParamsError() {
		return
	}
	if p.Phone != "" {
		uid, _, err := client.IsUserExistByPhone(p.Phone)
		if err != nil {
			LogPc.Error(b.DatabaseError(err.Error()))
			return
		}
		if uid != p.Uid {
			b.Res.Code = ErrUserAlreadyExist
			b.Res.Msg = MsgErrPhoneAlreadyBind
			b.Response()
			return
		}
	}

	updateData := map[string]interface{}{
		"vip": p.Vip,
	}
	_, err := client.UpdateUser(updateData, p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	msg := fmt.Sprintf("更新玩家(uid:%v)信息", p.Uid)
	b.NewLog(LogPlayer, OpUpdate, msg, updateData)
	if p.Phone != "" || p.Password != "" {
		data := map[string]interface{}{}
		if p.Password != "" {
			data["password"] = Md5sum(p.Password)
			_, err := client.UpdatePassport(data, p.Uid)
			if err != nil {
				LogPc.Error(b.DatabaseError(err.Error()))
				return
			}
		}
		if p.Phone != "" {
			data["phone"] = p.Phone
			_, err := client.UpdateUserPhone(p.Phone, p.Uid)
			if err != nil {
				LogPc.Error(b.DatabaseError(err.Error()))
				return
			}
		}
		b.NewLog(LogPlayer, OpUpdate, msg, data)
	}

	b.ResponseSuccess()
}

// @Title 玩家钻石购买流水
// @Description 玩家钻石购买流水
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   type         body   int     false      "0-所有,2-卖房卡(代充),3-卖房卡(直充),6-系统赠送"
// @Param   player_id    body   int     true       "玩家id"
// @Success 0 {object} []common.CardRecord 钻石流水列表
// @router /player/list-diamond-detail [post]
func (b *PublicController) ListPlayerDiamondDetail() {
	type Params struct {
		ListCardParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, count, err := pc.ListPlayerCardRecord(p.ListCardParams)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

//----------------------------------代理方面的-------------------------------------

// @Title 获取当前推广员的下属二级代理
// @Description 获取当前推广员的下属二级代理
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   uid          body   int     true       "代理id"
// @Param   is_formal    body   int     true       "是否正式的代理,0-表示所有代理,包括未激活的,1-表示正式的代理"
// @Success 0 {object} []common.H5User 代理用户列表
// @router /formal/list-child-agent [post]
func (b *PublicController) ListChildAgent() {
	type Params struct {
		ListParams
		Uid      int64 `json:"uid" valid:"Required"`
		IsFormal int64 `json:"is_formal" valid:"Range(0,1)"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	users, count, err := pc.ListChildAgent(p.ListParams, p.Uid, p.IsFormal)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	o := NewDBOrm(DBChessCenter)
	for _, v := range users {
		v["charge_amount"] = pc.StatAgentOrder(v["uid"], o)
	}

	b.Res.Data = users
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 代理详情
// @Description 代理详情
// @Param   agent_id     body   int     true       "代理的id"
// @Success 0 {object} []h5.CashRecord
// @router /formal/agent-detail [post]
func (b *PublicController) AgentDetail() {
	type Params struct {
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, err := pc.AgentDetail(p.AgentId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = cr
	b.ResponseSuccess()
}

// @Title 代理的提现记录
// @Description 代理的提现记录
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   agent_id     body   int     true       "代理的id"
// @Success 0 {object} []common.WithdrawRecord
// @router /formal/list-withdraw [post]
func (b *PublicController) ListWithdraw() {
	type Params struct {
		ListParams
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, count, err := h5.ListWithdraw(p.ListParams, p.AgentId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 代理钻石买卖流水
// @Description 代理钻石买卖流水
// @Param   agent_id     body   int     true      "代理uid"
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   type         body   int     false      "1-买房卡,2-卖房卡(代充),3-卖房卡(直充),4-送房卡,5-获赠房卡,6-系统赠送"
// @Param   player_id    body   int     false      "搜索玩家id"
// @Success 0 {object} []common.CardRecord 钻石流水列表
// @router /formal/list-diamond-detail [post]
func (b *PublicController) ListAgentDiamondDetail() {
	type Params struct {
		ListCardParams
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, count, err := h5.ListCardRecord(p.ListCardParams, p.AgentId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 代理(一级及二级)提成列表(首页中展示,因为二级代理产生的收益)
// @Description 代理(一级及二级)提成列表(首页中展示,因为二级代理产生的收益)
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   agent_id     body   int     true       "代理的id"
// @Success 0 {object} []common.CashRecord
// @router /formal/list-child-cash [post]
func (b *PublicController) ListChildCash() {
	type Params struct {
		ListParams
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	field := []string{"level"}
	u, err := h5.SpecifyUserInfoById(p.AgentId, field)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	if u == nil {
		b.ResponseFail("代理不存在,请检查代理id是否正确")
		return
	}

	if u.Level == Level1 {
		//一级代理提成列表(首页中展示,因为二级代理产生的收益)
		cr, count, err := h5.ListChildCash(p.ListParams, p.AgentId)
		if err != nil {
			LogPc.Error(b.DatabaseError(err.Error()))
			return
		}
		//查找二级代理或玩家(本级玩家直充产生的提成)
		field := []string{"nickname", "head_img_url"}
		for _, v := range cr {
			if v.UserType == Agent {
				u, err := h5.SpecifyUserInfoById(v.ChildId, field)
				if err != nil {
					LogPc.Error(err.Error())
				}
				if u != nil {
					v.Nickname = u.Nickname
					v.HeadImgUrl = u.HeadImgUrl
				} else {
					LogPc.Warning("h5_user里user表没有代理:%d,而h5里h5_cash_record里有", v.ChildId)
				}
			} else if v.UserType == Player {
				u, err := client.QueryUserInfoById(v.ChildId)
				if err != nil {
					LogPc.Error(err.Error())
				}
				v.Nickname = u.Nickname
				v.HeadImgUrl = u.ImageUrl
			}
		}
		b.Res.Data = cr
		b.Res.Count = count
		b.ResponseSuccess()
		return
	} else {
		//二级代理提成列表(首页中展示)
		cr, count, err := h5.ListLevel2Cash(p.ListParams, p.AgentId)
		if err != nil {
			LogPc.Error(b.DatabaseError(err.Error()))
			return
		}
		//查找玩家
		for _, v := range cr {
			u, err := client.QueryUserInfoById(v.ChildId)
			if err != nil {
				LogPc.Error(err.Error())
			}
			v.Nickname = u.Nickname
			v.HeadImgUrl = u.ImageUrl
		}
		b.Res.Data = cr
		b.Res.Count = count
		b.ResponseSuccess()
		return
	}

}

// @Title 代理的店铺玩家充值支付记录列表(H5店铺支付记录)
// @Description 代理的店铺玩家充值支付记录列表(H5店铺支付记录)
// @Param   agent_id           body   int     true       "代理的id"
// @Param   page_size          body   int     true       "每页显示数量"
// @Param   page_index         body   int     true       "第几页"
// @Param   start_time         body   int     false      "下单开始时间"
// @Param   end_time           body   int     false      "下单结束时间"
// @Param   uid          	   body   int     false      "玩家的id"
// @Param   transaction_id     body   string  false      "微信订单号"
// @Param   id                 body   int     false      "平台订单号"
// @Param   status             body   int     false      "订单状态,0-所有状态,1-未支付,2-已关闭,3-支付错误,4-支付成功,未发货,5-已发货'"
// @Success 0 {object} []common.Order 订单(支付)列表
// @router /formal/list-agent-shop-order [post]
func (b *PublicController) ListAgentShopOrder() {
	type Params struct {
		ListParams
		ListDayParams
		AllOrderParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	cr, count, err := pc.ListAgentShopOrder(p.ListParams, p.ListDayParams, p.AllOrderParams)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 金钱流水账(按月分)
// @Description 金钱流水账(按月分)
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   agent_id     body   int     true       "代理的id"
// @Success 0 {object} []h5.CashRecord
// @router /formal/list-cash-month [post]
func (b *PublicController) ListCashMonth() {
	type Params struct {
		ListParams
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, count, err := h5.ListMonth(p.ListParams, p.AgentId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 金钱流水账(每月详细帐单)
// @Description 金钱流水账(每月详细帐单)
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   month        body   int     true       "月份,1801表示2018年1月"
// @Param   agent_id     body   int     true       "代理的id"
// @Success 0 {object} []h5.CashRecord
// @router /formal/list-cash-detail [post]
func (b *PublicController) ListCashDetail() {
	type Params struct {
		ListCashParams
		AgentId int64 `json:"agent_id" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	cr, count, err := h5.ListDetail(p.ListCashParams, p.AgentId)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = cr
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取代理登录日志详细
// @Description 获取代理登录日志详细
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   uid          body   int     true       "代理id"
// @Param   start_time   body   int     false      "开始时间"
// @Param   end_time     body   int     false      "结束时间"
// @Success 0 {object} [] 登录日志
// @router /formal/list-agent-login-log [post]
func (b *PublicController) ListAgentLoginLog() {
	type Params struct {
		ListParams
		ListDayParams
		Uid int64 `json:"uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	users, count, err := pc.AgentLoginLog(p.ListParams, p.ListDayParams, p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = users
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取当前管理员管理的代理用户列表(正式的一级及二级代理)
// @Description 获取当前管理员管理的代理用户列表(正式的一级及二级代理)
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   group_id     body   int     false      "超级管理员时传这个参数"
// @Param   level        body   int     false      "0-所有代理,1-一级代理,2-二级代理"
// @Param   uid          body   int     false      "代理id"
// @Param   agent_name 	 body   string  false      "代理的名字"
// @Param   phone        body   string  false      "手机号"
// @Param   is_pass      body   int     false      "考核是否通过,0-所有,1-通过,2-不通过"
// @Param   is_frozen    body   int     false      "账号是否正常,0-所有,1-冻结,2-正常"
// @Param   order_name 	 body   string  false      "排序名字,total_card_num,card_num,open_fee"
// @Param   order        body   int     false      "1-升序,2-降序"
// @Success 0 {object} []common.H5User 代理用户列表
// @router /formal/list-official-h5user [post]
func (b *PublicController) ListOfficialH5User() {
	type Params struct {
		ListParams
		H5UserParams
		OrderParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	users, count, err := pc.ListOfficialH5User(p.ListParams, p.OrderParams, b.Ui.GroupId, p.H5UserParams)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	o := NewDBOrm(DBChessCenter)
	for _, v := range users {
		v["charge_amount"] = pc.StatAgentOrder(v["uid"], o)
		v["child_agent_num"] = pc.StatChildAgentNum(v["uid"], o)
	}

	b.Res.Data = users
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取某个具体的代理订单记录
// @Description 获取某个具体的代理订单记录
// @Param   start_time   body   int     false      "开始时间"
// @Param   end_time     body   int     false      "结束时间"
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   uid          body   int     true       "代理id"
// @Success 0 {object} []订单记录
// @router /formal/list-single-agent-order [post]
func (b *PublicController) ListSingleAgentOrder() {
	type Params struct {
		ListParams
		ListDayParams
		Uid int64 `json:"uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	order, count, amount, err := pc.ListSingleAgentOrder(p.ListParams, p.ListDayParams, p.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}

	b.Res.Data = map[string]interface{}{
		"order":  order,
		"amount": amount,
	}
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取某个具体的代理(渠道)的玩家
// @Description 获取某个具体的代理(渠道)的玩家
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   agent_uid    body   int     true       "代理id"
// @Success 0 {object} []订单记录
// @router /formal/list-agent-player [post]
func (b *PublicController) ListAgentPlayer() {
	type Params struct {
		ListParams
		AgentUid int64 `json:"agent_uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	ap, count, err := partner.ListAgentPlayerRelation(p.ListParams, p.AgentUid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = ap
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 获取某个具体的玩家推荐的玩家
// @Description 获取某个具体的玩家推荐的玩家
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Param   agent_uid    body   int     true       "玩家uid,为了方便，故意把玩家uid起名为agent_uid"
// @Success 0 {object} []订单记录
// @router /player/list-player-player [post]
func (b *PublicController) ListPlayerPlayer() {
	type Params struct {
		ListParams
		AgentUid int64 `json:"agent_uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	ap, count, err := partner.ListAgentPlayerRelation(p.ListParams, p.AgentUid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = ap
	b.Res.Count = count
	b.ResponseSuccess()
}
